﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;

namespace KC.DataAccess.IO
{
	public class Zip
	{
		public static string[] Unzip(string ZipFile, string DestinationPath)
		{
			if (string.IsNullOrEmpty(ZipFile)) throw new ArgumentNullException("ZipFile");
			if (string.IsNullOrEmpty(DestinationPath)) throw new ArgumentNullException("DestinationPath");
			ZipFile = ZipFile.Trim();
			DestinationPath = DestinationPath.Trim();
			if (!File.Exists(ZipFile)) throw new MissingMemberException("ZipFile");
			if (!Directory.Exists(DestinationPath)) Directory.CreateDirectory(DestinationPath);
			if (!DestinationPath.EndsWith("\\")) DestinationPath += "\\";
			List<string> files = new List<string>();

			ZipInputStream s = new ZipInputStream(File.OpenRead(ZipFile));
			ZipEntry theEntry = null;
			s.Position = 0;
			while (s.GetNextEntry() != null) {
				theEntry = s.GetNextEntry();
				string directoryName = Path.GetDirectoryName(theEntry.Name);
				string fileName = Path.GetFileName(theEntry.Name);

				Directory.CreateDirectory(DestinationPath + directoryName);
				if (fileName != String.Empty) {
					FileStream streamWriter = File.Create((DestinationPath + theEntry.Name));
					files.Add(theEntry.Name);
					int size = 2048;
					byte[] data = new byte[2048];
					while (true) {
						size = s.Read(data, 0, data.Length);
						if (size > 0) streamWriter.Write(data, 0, size);
						else break; }
					streamWriter.Close(); } }
			s.Close();
			return files.ToArray();
		}
	}
}
